from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.spit.models import Spit
from apps.spit.serializers import SpitSerializer


class SpitViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitSerializer

    # 匿名发表吐槽,禁用drf认证
    def perform_authentication(self, request):
        pass

    def retrieve(self, request, *args, **kwargs):
        spit = self.get_object()
        spit.visits += 1
        spit.save()
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            flag_collect = redis_conn.hget("spit_collect_%s" % user.id, str(id))
            flag_thumbup = redis_conn.hget("spit_thumbup_%s" % user.id, str(id))
            if flag_collect:
                spit.collected = True
            if flag_thumbup:
                spit.hasthumbup = True

        s = self.get_serializer(instance=spit)
        return Response(s.data)

    # 获取吐槽列表 spit/
    def list(self, request, *args, **kwargs):

        spitList = self.get_queryset().filter(parent=None).order_by("-publishtime")
        retSpitList = []

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spitList:
                flag_collect = redis_conn.hget("spit_collect_%s" % user.id, str(spit.id))
                flag_thumbup = redis_conn.hget("spit_thumbup_%s" % user.id, str(spit.id))
                if flag_collect:
                    spit.collected = True
                if flag_thumbup:
                    spit.hasthumbup = True

                retSpitList.append(spit)
        else:
            retSpitList = spitList

        s = self.get_serializer(instance=retSpitList, many=True)
        return Response(s.data)
